﻿using System;
using System.IO;
using System.Web;
using Microsoft.SharePoint;

namespace CodeCounsel.SharePoint.Flash
{
    public class FlvHandler
        : IHttpHandler
    {
        private static readonly byte[] _flvheader =
        {
            0x46, 0x4c, 0x56, // FLV
            0x01, // VERSION
            0x01, // FlAGS
            0x00, 0x00, 0x00, 0x09 // DATA OFFSET
        };

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string offsetString = context.Request.Params["start"];

            SPWeb site = SPContext.Current.Web;
            SPFile file = site.GetFile(context.Request.Url.ToString());

            long position;
            long length;

            if (String.IsNullOrEmpty(offsetString))
            {
                position = 0;
                length = file.Length;
            }
            else
            {
                position = Int64.Parse(offsetString);
                length = file.Length - position + _flvheader.Length;
            }

            context.Response.Buffer = false;
            context.Response.BufferOutput = false;

            context.Response.AppendHeader("Content-Type", "video/x-flv");
            context.Response.AddHeader("Content-Length", length.ToString());
            using (Stream fileStream = file.OpenBinaryStream())
            {
                if (position > 0)
                {
                    fileStream.Seek(position, SeekOrigin.Begin);
                    context.Response.OutputStream.Write(_flvheader, 0, _flvheader.Length);
                }
                int bufferSize = 16384;
                byte[] buffer = new byte[bufferSize];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    context.Response.OutputStream.Write(buffer, 0, bytesRead);
                    context.Response.OutputStream.Flush();
                }
            }
        }
    }
}
